//变量的生存周期
var func = function () {
    var a = 1;
    return function () {
        a++;
        console.log(a);
    }
}

var f = func();

f();
f();
f();
f();


var Type = {};

for (var i =0,type;type=['String','Array','Number'][i++];){
    (function (type) {
        Type['is'+type] = function (obj) {
            return Object.prototype.toString.call(obj) === '[object '+type+']';
        }
    })(type);
}

console.log(Type.isArray([]));
console.log(Type.isString('str'));

//变量的更多作用


var cache = {};

var mult= function () {
    var args = Array.prototype.join.call(arguments,',');
    if(cache[args]) return cache[args];
    var a = 1;
    for (var i=0;i<arguments.length;i++){
        a = a*arguments[i];
    }
    return cache[args] = a;
};

console.log(mult(1,2,3));
console.log(mult(3,4,5));

//将cache变量封装到函数内部

var mult = (function () {
    var cache = {};
    return function () {
        var args = Array.prototype.join.call(arguments,',');
        if(cache[args]) return cache[args];
        var a = 1;
        for (var i=0;i<arguments.length;i++){
            a = a*arguments[i];
        }
        return cache[args] = a;
    }
})();

console.log(mult(6,7,8,9));
console.log(mult(1,2,3));


//函数重构，提炼函数

var mult = (function () {
    var cache = {};
    var calculate = function () {
        var a = 1;
        for (var i=0;i<arguments.length;i++){
            a = a*arguments[i];
        }
        return a;
    }
    return function () {
        var args = Array.prototype.join.call(arguments,',');
        if(cache[args]) return cache[args];
        return cache[args] = calculate.apply(null,arguments);
    }
})();

console.log(mult(7,8,9,13));
console.log(mult(1,2,3,8));